package com.wlstock.funi.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.em.adapter.CommonAdapter;
import com.em.adapter.ViewHolder;
import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.fourmob.datetimepicker.date.DatePickerDialog.OnDateSetListener;
import com.sleepbot.datetimepicker.time.RadialPickerLayout;
import com.sleepbot.datetimepicker.time.TimePickerDialog;
import com.sleepbot.datetimepicker.time.TimePickerDialog.OnTimeSetListener;
import com.wlstock.funi.R;
import com.wlstock.funi.dao.SelfFundSetDao;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.model.SelfFundSetModel;
import com.wlstock.funi.utils.IntentContants;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

public class SelfFundSetAdapter extends CommonAdapter<SelfFundSetModel> implements OnClickListener, OnDateSetListener, OnTimeSetListener, CompoundButton.OnCheckedChangeListener {

	private static final int TYPE_PRICE = 1;
	private static final int TYPE_TOTAL = 2;

	private SimpleDateFormat dayFormat;
	private SimpleDateFormat timeFormat;
	private View curView;
	private DatePickerDialog dayPicker;
	private TimePickerDialog timePicker;
	private FragmentActivity mActivity;
	private int mode = -1;
	public onDeleteListener deleteListener;
	
	public SelfFundSetAdapter(Context context, List<SelfFundSetModel> datas,int layoutId, int mode) {
		super(context, datas, layoutId);
		Calendar calInstance = Calendar.getInstance();
		dayPicker = DatePickerDialog.newInstance(this, calInstance.get(Calendar.YEAR), calInstance.get(Calendar.MONTH), calInstance.get(Calendar.DAY_OF_MONTH));
		timePicker = TimePickerDialog.newInstance(this, calInstance.get(Calendar.HOUR_OF_DAY), calInstance.get(Calendar.MINUTE), true);
		this.mode = mode;
	}

	public SelfFundSetAdapter(FragmentActivity activity, List<SelfFundSetModel> datas,int layoutId,int mode) {
		super(activity, datas, layoutId);
		this.mActivity = activity;
		Calendar calInstance = Calendar.getInstance();
		
		dayPicker = DatePickerDialog.newInstance(this, calInstance.get(Calendar.YEAR), calInstance.get(Calendar.MONTH), calInstance.get(Calendar.DAY_OF_MONTH));
		timePicker = TimePickerDialog.newInstance(this, calInstance.get(Calendar.HOUR_OF_DAY), calInstance.get(Calendar.MINUTE), true);
		this.mode = mode;
	}
	
	@Override
	public void convert(ViewHolder holder, SelfFundSetModel model) {
		dayFormat = new SimpleDateFormat("MM-dd");
		timeFormat = new SimpleDateFormat("HH:mm");
		EditText ed_stk_price = (EditText)holder.getView(R.id.ed_stk_price);
		ed_stk_price.addTextChangedListener(new Watcher(ed_stk_price, model,TYPE_PRICE));
		EditText ed_total_money = holder.getView(R.id.ed_total_money);
		ed_total_money.addTextChangedListener(new Watcher(ed_total_money, model, TYPE_TOTAL));

		holder.setText(R.id.tv_stkname, model.getStkName());
		holder.setText(R.id.tv_stkcode, "("+model.getStkNo()+")");
		holder.setText(R.id.ed_stk_price, String.valueOf(model.getPrice()));
		holder.setText(R.id.tv_start_day, dayFormat.format(model.getStartDay()));
		holder.setText(R.id.tv_end_day, dayFormat.format(model.getEndDay()));
		holder.setText(R.id.tv_start_time, model.getStartTime());
		holder.setText(R.id.tv_end_time, model.getEndTime());
		holder.setText(R.id.ed_total_money,model.getTotalMoney()+"");
		CheckBox cb_quick_buy = (CheckBox) holder.getView(R.id.cb_quick_buy);
		cb_quick_buy.setChecked(model.isQuickBuy());
		cb_quick_buy.setOnCheckedChangeListener(this);

		if (model.getTradeType() == OperateModel.TradeType_BUY) {
			holder.setText(R.id.tv_trade_type, "买入");
			cb_quick_buy.setVisibility(View.VISIBLE);
		}else if (model.getTradeType() == OperateModel.TradeType_SELL) {
			holder.setText(R.id.tv_trade_type, "卖出");
			cb_quick_buy.setVisibility(View.GONE);
		}else {
			if (this.mode == IntentContants.INTENT_MODE_SAILE) {
				holder.setText(R.id.tv_trade_type, "卖出");
				cb_quick_buy.setVisibility(View.GONE);
			}else if(this.mode == IntentContants.INTENT_MODE_BUY) {
				holder.setText(R.id.tv_trade_type, "买入");
				cb_quick_buy.setVisibility(View.VISIBLE);
			}else {
				holder.setText(R.id.tv_trade_type,""+mode);
			}
		}
		
		holder.setOnClickListener(R.id.layout_specific_set, this);
		holder.setOnClickListener(R.id.tv_start_day, this);
		holder.setOnClickListener(R.id.tv_end_day, this);
		holder.setOnClickListener(R.id.tv_start_time, this);
		holder.setOnClickListener(R.id.tv_end_time, this);
		holder.setOnClickListener(R.id.tv_trade_type, this);
		
		holder.setTags(model);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		Log.i("TAG", "dd");
		return super.getView(position, convertView, parent);
	}



	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		curView = v;
		switch (curView.getId()) {
		case R.id.tv_start_day:
		case R.id.tv_end_day:
			dayPicker.setCloseOnSingleTapDay(true);
			dayPicker.setYearRange(2014, 2017);
			if (!dayPicker.isAdded()) {
				dayPicker.show(mActivity.getSupportFragmentManager(), "DAY_PICKER");	
			}
			break;
		case R.id.tv_start_time:
		case R.id.tv_end_time:
			timePicker.setCloseOnSingleTapMinute(true);
			if (!timePicker.isAdded()) {
				timePicker.show(mActivity.getSupportFragmentManager(), "TIME_PICKER");	
			}
			break;
		case R.id.layout_specific_set:
			final SelfFundSetModel selectModel = (SelfFundSetModel) v.getTag();
			new AlertDialog.Builder(mContext).setTitle("是否删除").setMessage("删除"+selectModel.getStkName()+"  "+selectModel.getStartTime()+"至"+selectModel.getEndTime()+"设置?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					SelfFundSetDao.getInstance(mContext).deleteStk(selectModel.getId(),selectModel.getStkNo());
					getmDatas().remove(selectModel);
					if (deleteListener!=null){
						deleteListener.onDelete(selectModel);
					}
					notifyDataSetChanged();
				}
			}).setNegativeButton("取消", null).show();
			break;
		case R.id.tv_trade_type:
			SelfFundSetModel model = (SelfFundSetModel) v.getTag();
			TextView tv = (TextView) v;
			if (model.getTradeType() == OperateModel.TradeType_BUY) {
				model.setTradeType(OperateModel.TradeType_SELL);
				tv.setText("卖出");
			}else {
				model.setTradeType(OperateModel.TradeType_BUY);
				tv.setText("买入");
			}
			notifyDataSetInvalidated();
			if (deleteListener!=null){
				deleteListener.onDelete(null);
			}
			break;
		default:
			break;
		}
	}


	@Override
	public void onDateSet(DatePickerDialog datePickerDialog, int year,int month, int day) {
		SelfFundSetModel model = (SelfFundSetModel) curView.getTag();
		//这里只去到月日，没有取年，未来可能存在问题
		month = month + 1;
		String select = month+"-"+day;
		switch (curView.getId()) {
		case R.id.tv_start_day:
			try {
				model.setStartDay(dayFormat.parse(select));
				((TextView)curView).setText(select);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case R.id.tv_end_day:
			try {
				model.setEndDay(dayFormat.parse(select));
				((TextView)curView).setText(select);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
		
		curView = null;
	}



	@Override
	public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
		SelfFundSetModel model = (SelfFundSetModel) curView.getTag();
		String select = hourOfDay + ":" + minute;
		switch (curView.getId()) {
		case R.id.tv_start_time:
			model.setStartTime(select);
			((TextView)curView).setText(select);
			break;
		case R.id.tv_end_time:
			model.setEndTime(select);
			((TextView)curView).setText(select);
			break;
		default:
			break;
		}
		curView = null;
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		SelfFundSetModel tag = (SelfFundSetModel) buttonView.getTag();
		tag.setQuickBuy(isChecked);
	}


	public class Watcher implements TextWatcher{
		private EditText ed;
		private SelfFundSetModel fundSetModel;
		private int edType;
		
		public Watcher(EditText ed,SelfFundSetModel model, int edType) {
			this.ed = ed;
			this.fundSetModel = model;
			this.edType = edType;
		}
		
		@Override
		public void afterTextChanged(Editable arg0) {
			try {
				SelfFundSetModel model = (SelfFundSetModel) ed.getTag();
				if (model!=null) {
					if (edType == TYPE_PRICE){
						model.setPrice(Float.valueOf(arg0.toString()));
					}else if(edType == TYPE_TOTAL){
						model.setTotalMoney(Long.valueOf(arg0.toString()));
					}
				}
			} catch (Exception e) {
			}
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			
		}

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			
		}
		

	}

	public interface onDeleteListener{
		public void onDelete(SelfFundSetModel model);
	}
	
}
